package 纯数组;

import com.alibaba.fastjson.JSON;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-10-08
 **/

public class No289生命游戏 {

    private int[][] board;
    private int allLength;
    private int itemLength;

    public void gameOfLife(int[][] board) {

        this.board = board;
        this.allLength = board.length;
        this.itemLength = board[0].length;
        int[][] arr = new int[allLength][itemLength];

        for (int i = 0; i < allLength; i++) {
            for (int j = 0; j < itemLength; j++) {
                if (isLive(i , j)) {
                    arr[i][j] = 1;
                } else {
                    arr[i][j] = 0;
                }
            }
        }

        for (int i = 0; i < allLength; i++) {
            for (int j = 0; j < itemLength; j++) {
                board[i][j] = arr[i][j];
            }
        }
    }

    private boolean isLive(int x, int y) {
        // 先检验周围有多少个细胞
        int count = this.getCount(x, y);
        if (count < 2) {
            return false;
        }
        if (count == 2) {
            return board[x][y] == 1;
        }
        if (count == 3) {
            return true;
        }
        return false;
    }

    // 周围细胞数量
    private int getCount(int x, int y) {
        int count = 0;
        // 上左下右边界
        boolean top = x > 0;
        boolean left = y > 0;
        boolean bottom = x < allLength - 1;
        boolean right = y < itemLength - 1;
        // 上
        if (top) {
            if (board[x - 1][y] == 1) {
                count++;
            }
        }
        // 下
        if (bottom) {
            if (board[x + 1][y] == 1) {
                count++;
            }
        }
        // 左
        if (left) {
            if (board[x][y - 1] == 1) {
                count++;
            }
        }
        // 右
        if (right) {
            if (board[x][y + 1] == 1) {
                count++;
            }
        }
        // 左上
        if (left && top) {
            if (board[x - 1][y - 1] == 1) {
                count++;
            }
        }
        // 右上
        if (right && top) {
            if (board[x - 1][y + 1] == 1) {
                count++;
            }
        }
        // 左下
        if (left && bottom) {
            if (board[x + 1][y - 1] == 1) {
                count++;
            }
        }
        // 右下
        if (right && bottom) {
            if (board[x + 1][y + 1] == 1) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        No289生命游戏 n = new No289生命游戏();
        int[][] arr = {{0,1,0},{0,0,1},{1,1,1},{0,0,0}};
        n.gameOfLife(arr);
        System.out.println(JSON.toJSONString(arr));
    }

}
